import React, {useState, useEffect} from 'react';
import {Text, TextInput, ToastAndroid, View} from 'react-native';

import Checkbox from 'teaset/components/Checkbox/Checkbox';
import ColorConstants from '../resources/ColorConstants';
import {post} from '../http/http';
import ColorButton from '../components/ColorButton';

const CabinetExamPage = props => {
  const [examInfo, setExamInfo] = useState(null);
  const [fillParams, setFillParams] = useState(null);
  const [paper, setPaper] = useState(null);
  const [password, setPassword] = useState('');
  const [papers, setPapers] = useState(null);
  const [userPapers, setUserPapers] = useState(null);
  const [topicOutLineList, setTopicOutLineList] = useState(null);
  const [curPage, setCurPage] = useState(0);
  const [topicIndex, setTopicIndex] = useState(0);
  const [resultPapers, setResultPapers] = useState(null);

  useEffect(() => {
    loadData();
  }, []);

  const loadData = async () => {
    try {
      const {data} = await post(
        '/examPaper/examinationUserPapersApi/api/findUserExaminationPapersInfoApi?route=examPaper',
        {
          papersId: props.getParam('papersId'),
        },
      );
      props.hideLoading(false);
      setExamInfo(data);
      setFillParams(data.fillParams);
      setPaper(data.paper);
      if (data.paper.participationMode === 0 && data.fillParams.length === 0) {
        startExam();
      }
    } catch (e) {
      props.showErrorMessage(e.message);
    }
  };

  const startExam = async () => {
    try {
      const {data} = await post(
        '/assets/materialCabinetExamUserPapersApi/api/startUserExamPapersApi',
        {
          curriculumResourceId: examInfo.curriculumResourceId,
          papersId: paper.papersId,
          password: password,
          examinationUserFillParamsStr: JSON.stringify(fillParams),
          isStart: true,
          relId: props.getParam('relId'),
        },
      );
      setPapers(data.examinationPapers);
      setUserPapers(data.examinationUserPapers);
      setTopicOutLineList(data.topicOutLineList);
    } catch (e) {
      ToastAndroid.show(e.message, ToastAndroid.SHORT);
    }
  };

  const topicTypeName = type => {
    switch (type) {
      case 0:
        return '单选题';
      case 1:
        return '多选题';
      case 2:
        return '简答题';
      case 3:
        return '不定项题';
      case 4:
        return '填空题';
      case 5:
        return '判断题';
      default:
        return '';
    }
  };

  const renderTopicContent = question => {
    const type = question.bankType;
    if (type === 0) {
      // 单选题
      return (
        <View>
          {question.options.map(option => (
            <Checkbox
              title={`${option.optionSort}、${option.optionName}`}
              checked={option.isCheck === 1}
              titleStyle={{fontSize: 20}}
              disabled={userPapers.isSubmitPaper}
              onChange={value => {
                question.options.forEach(v => (v.isCheck = 0));
                option.isCheck = value ? 1 : 0;
                if (value) {
                  post(
                    '/assets/materialCabinetExamUserPapersApi/api/saveExamUserOptionApi',
                    {
                      userPagersId: userPapers.userPapersId,
                      papersId: paper.papersId,
                      bankId: question.bankId,
                      examinationUserOptionStr: JSON.stringify([
                        {optionId: option.optionId},
                      ]),
                    },
                  );
                }
              }}
            />
          ))}
        </View>
      );
    } else if (type === 1 || type === 3) {
      // 多选题 不定项题
      return (
        <View>
          {question.options.map(option => (
            <Checkbox
              title={`${option.optionSort}、${option.optionName}`}
              checked={option.isCheck === 1}
              disabled={userPapers.isSubmitPaper}
              titleStyle={{fontSize: 20}}
              onChange={value => {
                option.isCheck = value ? 1 : 0;
                if (value) {
                  post(
                    '/assets/materialCabinetExamUserPapersApi/api/saveExamUserOptionApi',
                    {
                      userPagersId: userPapers.userPapersId,
                      papersId: paper.papersId,
                      bankId: question.bankId,
                      examinationUserOptionStr: JSON.stringify(
                        question.options
                          .filter(v => v.isCheck)
                          .map(v => ({optionId: v.optionId})),
                      ),
                    },
                  );
                }
              }}
            />
          ))}
        </View>
      );
    } else if (type === 2) {
      return (
        <View>
          <TextInput
            editable={userPapers.isSubmitPaper !== 1}
            style={{
              color: userPapers.isSubmitPaper ? '#c0c4cc' : '#666',
              backgroundColor: '#f5f7fa',
              borderColor: '#e4e7ed',
              borderWidth: 1.5,
              minHeight: 100,
              fontSize: 20,
            }}
            value={
              question.options && question.options.length > 0
                ? question.options[0].optionAnswer
                : ''
            }
            onChangeText={v => {
              post(
                '/assets/materialCabinetExamUserPapersApi/api/saveExamUserOptionApi',
                {
                  userPagersId: userPapers.userPapersId,
                  papersId: paper.papersId,
                  bankId: question.bankId,
                  examinationUserOptionStr: JSON.stringify([{optionAnswer: v}]),
                },
              );
            }}
          />
        </View>
      );
    } else if (type === 4) {
      return (
        <View>
          <TextInput
            editable={userPapers.isSubmitPaper !== 1}
            style={{
              color: userPapers.isSubmitPaper ? '#c0c4cc' : '#666',
              backgroundColor: '#f5f7fa',
              borderColor: '#e4e7ed',
              borderWidth: 1.5,
              minHeight: 100,
              fontSize: 20,
            }}
            placeholder={'多个答案请用英文逗号隔开'}
            value={
              question.options && question.options.length > 0
                ? question.options[0].optionAnswer
                : ''
            }
            onChangeText={v => {
              post(
                '/assets/materialCabinetExamUserPapersApi/api/saveExamUserOptionApi',
                {
                  userPagersId: userPapers.userPapersId,
                  papersId: paper.papersId,
                  bankId: question.bankId,
                  examinationUserOptionStr: JSON.stringify([{optionAnswer: v}]),
                },
              );
            }}
          />
        </View>
      );
    } else if (type === 5) {
      return (
        <View>
          {(question.options.length === 0
            ? [
                {optionId: 1, optionName: '正确'},
                {optionId: 2, optionName: '错误'},
              ]
            : question.options
          ).map(option => (
            <Checkbox
              title={`${option.optionName}`}
              checked={option.userOptionIsok}
              titleStyle={{fontSize: 20}}
              disabled={userPapers.isSubmitPaper}
              onChange={value => {
                question.options.forEach(v => (v.userOptionIsok = false));
                option.userOptionIsok = value;
                if (value) {
                  post(
                    '/assets/materialCabinetExamUserPapersApi/api/saveExamUserOptionApi',
                    {
                      userPagersId: userPapers.userPapersId,
                      papersId: paper.papersId,
                      bankId: question.bankId,
                      examinationUserOptionStr: JSON.stringify([
                        {optionIsok: option.optionId, optionId: ''},
                      ]),
                    },
                  );
                }
              }}
            />
          ))}
        </View>
      );
    }
    return null;
  };

  const renderTopicList = () => {
    if (papers) {
      if (papers.papersShowPattern === 1) {
        const pages = topicOutLineList;
        if (pages && pages.length > 0) {
          const topics = pages[curPage].questionBankList;
          return (
            <View>
              {topics
                .slice(topicIndex, topicIndex + 1)
                .map((question, index) => (
                  <View style={{borderTopColor: '#eee', borderTopWidth: 1}}>
                    <View
                      style={{
                        justifyContent: 'space-between',
                        flexDirection: 'row',
                        alignItems: 'center',
                        padding: 15,
                        backgroundColor: '#f2f2f2',
                      }}>
                      <Text style={{fontSize: 26}}>
                        试题名称: {pages[curPage].topicOutlineName}
                      </Text>
                      <Text>
                        (共{pages[curPage].totalQuestionNum}题
                        {papers.papersShowPattern === 1
                          ? `，当前第${topicIndex + 1}题,`
                          : ','}
                        共{pages[curPage].totalScore}分)
                      </Text>
                    </View>
                    <View style={{marginTop: 10, flexDirection: 'row'}}>
                      <Text style={{color: '#666', fontSize: 20}}>
                        {topicTypeName(question.bankType)}({question.score}分)
                      </Text>
                      {userPapers.isSubmitPaper || resultPapers ? (
                        <Text
                          style={{
                            color: 'red',
                            fontSize: 20,
                            marginLeft: 30,
                          }}>
                          得分: {question.userGetScore || 0}
                        </Text>
                      ) : null}
                    </View>
                    <View style={{marginTop: 10}}>
                      <Text style={{color: '#444', fontSize: 20}}>
                        {index + 1}、{question.bankName}
                      </Text>
                    </View>
                    {renderTopicContent(question)}
                    {userPapers.isSubmitPaper || resultPapers ? (
                      <View style={{marginTop: 10, marginBottom: 10}}>
                        <Text style={{fontSize: 20}}>
                          正确答案: {question.bankAnswer}
                        </Text>
                      </View>
                    ) : null}
                    {userPapers.isSubmitPaper !== 1 &&
                    papers.papersShowPattern === 0 ? (
                      <View
                        style={{
                          justifyContent: 'center',
                          alignItems: 'center',
                          width: '100%',
                        }}>
                        <ColorButton
                          onPress={submitExam}
                          style={{marginVertical: 30}}>
                          提交
                        </ColorButton>
                      </View>
                    ) : null}
                    <View
                      style={{
                        width: '100%',
                        justifyContent: 'center',
                        alignItems: 'center',
                        flexDirection: 'row',
                      }}>
                      <ColorButton
                        onPress={previewPage}
                        containerStyle={{
                          paddingHorizontal: 20,
                          marginHorizontal: 30,
                        }}
                        disabled={curPage === 0 && topicIndex === 0}>
                        上一题
                      </ColorButton>
                      {curPage === pages.length - 1 &&
                      topicIndex === topics.length - 1 ? (
                        <ColorButton
                          onPress={submitExam}
                          style={{
                            marginHorizontal: 30,
                            paddingHorizontal: 20,
                          }}>
                          提交
                        </ColorButton>
                      ) : (
                        <ColorButton
                          onPress={nextPage}
                          containerStyle={{
                            paddingHorizontal: 20,
                            marginHorizontal: 30,
                          }}
                          disabled={
                            curPage === pages.length - 1 &&
                            topicIndex === topics.length - 1
                          }>
                          下一题
                        </ColorButton>
                      )}
                    </View>
                  </View>
                ))}
            </View>
          );
        }
      } else {
        const pages = topicOutLineList;
        if (pages && pages.length > 0) {
          return (
            <View
              style={{alignItems: 'stretch', width: '80%', marginLeft: '10%'}}>
              <View
                style={{
                  justifyContent: 'space-between',
                  flexDirection: 'row',
                  alignItems: 'center',
                  padding: 15,
                  backgroundColor: '#f2f2f2',
                }}>
                <Text style={{fontSize: 26}}>
                  试题名称: {papers.papersName}
                </Text>
                <Text>
                  (共{pages.flatMap(v => v.questionBankList).length}题,共
                  {papers.totalScore}分)
                </Text>
              </View>
              {pages.map((page, idx) => {
                const topics = page.questionBankList;
                return (
                  <View>
                    {topics.map((question, index) => (
                      <View style={{borderTopColor: '#eee', borderTopWidth: 1}}>
                        <View style={{marginTop: 10, flexDirection: 'row'}}>
                          <Text style={{color: '#666', fontSize: 20}}>
                            {topicTypeName(question.bankType)}({question.score}
                            分)
                          </Text>
                          {userPapers.isSubmitPaper || resultPapers ? (
                            <Text
                              style={{
                                color: 'red',
                                fontSize: 20,
                                marginLeft: 30,
                              }}>
                              得分: {question.userGetScore || 0}
                            </Text>
                          ) : null}
                        </View>
                        <View style={{marginTop: 10}}>
                          <Text style={{color: '#444', fontSize: 20}}>
                            {index + 1}、{question.bankName}
                          </Text>
                        </View>
                        {renderTopicContent(question)}
                        {userPapers.isSubmitPaper || resultPapers ? (
                          <View style={{marginTop: 10, marginBottom: 10}}>
                            <Text style={{fontSize: 20}}>
                              正确答案: {question.bankAnswer}
                            </Text>
                          </View>
                        ) : null}
                      </View>
                    ))}
                  </View>
                );
              })}
              {userPapers.isSubmitPaper !== 1 &&
              papers.papersShowPattern === 0 &&
              !resultPapers ? (
                <ColorButton
                  onPress={submitExam}
                  containerStyle={{marginVertical: 30}}
                  fontSize={20}
                  title={'提交'}
                />
              ) : null}
              {resultPapers ? (
                <View
                  style={{width: '100%', marginTop: 30, alignItems: 'center'}}>
                  {resultPapers.isPass ? (
                    <Text
                      style={{
                        color: ColorConstants.primaryColor(),
                        fontSize: 20,
                        fontWeight: 'bold',
                      }}>
                      恭喜过关,可以开门领取(得分:
                      {resultPapers.userExaminationScore}分)
                    </Text>
                  ) : (
                    <Text
                      style={{color: 'red', fontSize: 20, fontWeight: 'bold'}}>
                      请重新答题,谢谢(得分:
                      {resultPapers.userExaminationScore}分)
                    </Text>
                  )}
                  {resultPapers.isPass ? (
                    <ColorButton
                      title={'开门领取'}
                      containerStyle={{marginTop: 20, paddingHorizontal: 30}}
                      fontSize={20}
                      onPress={() => {
                        props.executeCompletion(userPapers.userPapersId);
                        props.navigation.goBack();
                      }}
                    />
                  ) : (
                    <ColorButton
                      onPress={() => {
                        setResultPapers(null);
                        setPapers(null);
                        setUserPapers(null);
                        setTopicOutLineList(null);
                        setExamInfo(null);
                        setFillParams(null);
                        setPaper(null);
                        loadData();
                      }}
                      containerStyle={{marginTop: 20, paddingHorizontal: 30}}
                      fontSize={20}
                      title={'重新考试'}
                    />
                  )}
                </View>
              ) : null}
            </View>
          );
        }
      }
    }
  };

  const submitExam = async () => {
    try {
      const {data} = await post(
        '/assets/materialCabinetExamUserPapersApi/api/submitExaUserPapersApi',
        {
          userPagersId: userPapers.userPapersId,
        },
      );
      ToastAndroid.show('提交成功', ToastAndroid.SHORT);
      setResultPapers(data.examinationUserPapers);
    } catch (e) {
      ToastAndroid.show(e.message, ToastAndroid.SHORT);
    }
  };

  const previewPage = () => {
    const list = topicOutLineList;
    if (topicIndex === 0 && curPage > 0) {
      setCurPage(curPage - 1);
      setTopicIndex(list[curPage - 1].questionBankList.length - 1);
    } else {
      setTopicIndex(topicIndex - 1);
    }
  };

  const nextPage = () => {
    const questionList = topicOutLineList[curPage].questionBankList;
    if (topicIndex === questionList.length - 1) {
      setCurPage(curPage + 1);
      setTopicIndex(0);
    } else {
      setTopicIndex(topicIndex + 1);
    }
  };

  const renderEnterView = () => {
    if (paper && !papers) {
      return (
        <View style={{width: '100%'}}>
          <Text
            style={{
              textAlign: 'center',
              fontSize: 18,
              fontWeight: 'bold',
              marginTop: 15,
            }}>
            {paper.papersName}
          </Text>
          <Text
            style={{
              color: '#666',
              fontSize: 14,
              textAlign: 'center',
              marginVertical: 15,
            }}>
            {paper.examinationNotes}
          </Text>
          {paper.participationMode === 1 ? (
            <View
              style={{
                flexDirection: 'row',
                borderWidth: 1,
                borderColor: '#eee',
                borderRadius: 8,
                paddingRight: 10,
              }}>
              <Text
                style={{
                  backgroundColor: '#f5f7fa',
                  color: '#909399',
                  padding: 10,
                  width: 100,
                }}>
                练习口令：
              </Text>
              <TextInput
                secureTextEntry
                value={this.state.password}
                onChangeText={v => this.setState({password: v})}
                placeholder="请输入口令"
                style={{flex: 1, padding: 10}}
              />
            </View>
          ) : null}
          {this.state.fillParams.map(value => {
            return (
              <View
                style={{
                  flexDirection: 'row',
                  marginTop: 10,
                  borderWidth: 1,
                  borderColor: '#eee',
                  borderRadius: 8,
                  paddingRight: 10,
                }}>
                <Text
                  style={{
                    backgroundColor: '#f5f7fa',
                    color: '#909399',
                    padding: 10,
                    width: 100,
                  }}>
                  {value.fillParamsName}
                </Text>
                <TextInput
                  style={{flex: 1, padding: 10}}
                  placeholder="请输入值"
                  value={value.fillParamsValue}
                  onChangeText={v => (value.fillParamsValue = v)}
                />
              </View>
            );
          })}
          <ColorButton
            onPress={this.startExam}
            containerStyle={{marginTop: 30, marginHorizontal: 50}}
            style={{fontSize: 30}}
            height={60}>
            立即考试
          </ColorButton>
        </View>
      );
    }
    return null;
  };
  return (
    <View style={{flex: 1, width: '100%', alignItems: 'center'}}>
      {renderEnterView()}
      {renderTopicList()}
    </View>
  );
};
export default CabinetExamPage;
